<template>
    <van-nav-bar title="编辑收货地址" left-text="" left-arrow @click-left="goBack" />
    <van-address-edit :area-list="areaList" show-set-default show-delete
        :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave" :address-info="info" @delete="onDelete" />

</template>

<script setup>
import { areaList } from '@vant/area-data';
const { proxy } = getCurrentInstance()
const goBack = () => { proxy.$router.go(-1) }
const LoginUser = reactive(proxy.$cookies.get('LoginUser') ?? {})
const addid = proxy.$route.query.addid ? proxy.$route.query.addid : 0;
const info = ref({})

onBeforeMount(() => {
    getAddressInfoData();
})

const getAddressInfoData = async () => {
    let result = await Api.AddressInfo({
        busid: LoginUser.id,
        addid: addid
    })

    if (result.code == 1) {
        let data = result.data

        info.value = {
            name: data.consignee,
            tel: data.mobile,
            areaCode: data.district,
            addressDetail: data.address,
            isDefault: data.status == '1' ? true : false
        }
    }
}

const onSave = async (val) => {
    let data = {
        busid: LoginUser.id,
        consignee: val.name,
        mobile: val.tel,
        status: val.isDefault == true ? '1' : '0',
        address: val.addressDetail,
        code: val.areaCode,
        addid: addid
    }
    let result = await Api.AddressEdit(data)
    if (result.code == 1) {
        success({
            message: result.msg,
            onClose: () => {
                goBack()
            }
        });
    }
    else {
        error(result.msg);
    }
}

const onDelete = () => {
    Dialog({
        message:
            '确认是否删除当前收货地址?',
    })
        .then(async () => {
            let result = await Api.AddressDel({
                busid: LoginUser.id,
                addid: addid
            })
            if (result.code == 1) {
                success({
                    message: result.msg,
                    onClose: () => {
                        goBack()
                    }
                });
            }
            else {
                error(result.msg);
            }
        })
        .catch(() => { });
}
</script>